<template>
  <div>
    <sec-form
      ref="formRef"
      :hideProp="hideProp"
      :ruleForm="ruleForm"
      :formData="formData"
      :rules="rules"
      :span="12"
      :optionData="optionData"
    >
      <template v-slot:content>
        <!-- <button @click="previewData">print html</button> -->
        <div>
          <html-editor :htmlValue="ruleForm.content" ref="htmlEditor" @editorChange="editorChange" />
        </div>
      </template>
      <template v-slot:msgTemplatePreview>
        <!-- <button @click="getVariablesListData">getVariablesListData</button> -->
        <!-- <button @click="setVariables">setVariables</button> -->
        <iframe
          id="msgTemplatePreviewIframe"
          :src="iframeUrl"
          frameborder="0"
          ref="msgTemplatePreviewRef"
          style="border: 1px solid #dcdfe6; border-radius: 4px; width: 100%; height: 300px"
        >
        </iframe>
      </template>
      <template v-slot:variablesList>
        <div>
          <variables-list
            ref="variablesListRef"
            :templateContent="templateMap.get(ruleForm.templateId).content"
            :variables="templateMap.get(ruleForm.templateId).variables"
            @getVariables="getVariables"
          ></variables-list>
        </div>
      </template>
      <template v-slot:operation>
        <el-button @click="save">{{ $t("保存") }}</el-button>
        <el-tooltip class="item" effect="dark" :content="$t('向自己发一份触达，用以预览效果')" placement="top-start">
          <el-button type="primary" @click="previewTouchSource">{{ $t("预览") }}</el-button>
        </el-tooltip>
      </template>
    </sec-form>
  </div>
</template>

<script>
import {
  touchInsertApi,
  msgSenderListApi,
  msgTemplateListApi,
  msgTemplateDetailApi,
  previewTouchApi,
  detailTaskApi,
} from "api/dataCenter.js";
import { validContent, validInteger, validReceiver } from "utils/validate.js";

import HtmlEditor from "views/touch/myEditor.vue";
import VariablesList from "views/touch/variablesList";

export default {
  components: { HtmlEditor, VariablesList },
  props: { touchId: Number },
  data() {
    return {
      ruleForm: {
        msgChannel: 2,
        templateId: "",
        variables: "",
        content: "",
      },
      formData: [
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("任务标题"),
          prop: "title",
        },
        {
          type: "text",
          clearable: true,
          filterable: true,
          label: this.$t("消息跟催Id"),
          prop: "followId",
          span: 12,
        },
        {
          type: "select",
          clearable: true,
          filterable: true,
          label: this.$t("邮件模版"),
          prop: "templateId",
          span: 24,
        },
        {
          type: "select",
          clearable: true,
          filterable: true,
          label: this.$t("发送账号"),
          prop: "msgAccountId",
          span: 24,
        },
        {
          type: "textarea",
          clearable: true,
          rows: 4,
          label: this.$t("任务接收者"),
          span: 24,
          prop: "receiver",
          placeholder: "请输入账号（邮箱前缀）多个账号请使用英文逗号分隔；示例：zhangsan,lisi,wangwu,laoliu",
        },
        {
          type: "slot",
          prop: "content",
          span: 24,
          label: this.$t("任务内容"),
        },
        {
          type: "slot",
          clearable: true,
          label: this.$t("邮件模板预览"),
          prop: "msgTemplatePreview",
          span: 24,
        },
        {
          type: "slot",
          label: this.$t("模版变量"),
          prop: "variablesList",
          span: 24,
        },
        {
          type: "slot",
          prop: "operation",
          style: { "text-align": "center" },
          span: 24,
        },
      ],
      hideProp: {
        msgTemplatePreview: true,
        variablesList: true,
      },
      optionData: { msgAccountId: [], templateId: [] },
      rules: {
        title: [{ required: true, message: this.$t("请输入任务标题"), trigger: "blur" }],
        followId: [{ validator: validInteger, trigger: "blur" }],
        msgAccountId: [{ required: true, message: this.$t("请选择发送账号"), trigger: "blur" }],
        receiver: [{ required: true, validator: validReceiver, trigger: "blur" }],
        content: [{ required: true, validator: validContent, trigger: "blur" }],
      },
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: false, //标题
        underline: false, // 下划线
        strikethrough: true, // 中划线
        mark: false, // 标记
        superscript: false, // 上角标
        subscript: false, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: false, // 图片链接
        code: true, // 代码块
        table: false, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: false, // 展示html源码
        help: false, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: false, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: false, // 导航目录
        /* 2.1.8 */
        alignleft: false, // 左对齐
        aligncenter: false, // 居中
        alignright: false, // 右对齐
        /* 2.2.1 */
        subfield: false, // 单双栏模式
        preview: true, // 预览
      },
      iframeUrl: "",
      templateContent: "",
      templateMap: "",
    };
  },
  watch: {
    "ruleForm.templateId": {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        // console.log(newVal, oldVal);
        if (newVal) {
          this.hideProp.msgTemplatePreview = false;
          this.hideProp.variablesList = false;
          this.hideProp.content = true;
          this.iframeUrl = "/space/msgTemplatePreview?id=" + newVal;
        } else {
          this.hideProp.msgTemplatePreview = true;
          this.hideProp.variablesList = true;
          this.hideProp.content = false;
        }
      },
    },
    touchId: {
      deep: true,
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.initOptionData();
        }
      },
    },
  },
  computed: {},
  methods: {
    editorChange(editor) {
      this.editor = editor;
      this.ruleForm.content = editor.getHtml();
      this.ruleForm.previewContent = !editor.isEmpty();
    },
    initOptionData() {
      msgTemplateListApi({ pageNum: 1, pageSize: 99 }).then((res) => {
        let map = new Map();
        this.optionData.templateId = res.data.list.map(function (item, index, array) {
          // 解构赋值
          let { id, name, content } = item;
          let value = { content, variables: "" };
          map.set(id, value);
          return { label: name, value: id };
        });
        this.templateMap = map;
        if (this.touchId) {
          this.initTouchData();
        }
      });
      msgSenderListApi().then((res) => {
        this.optionData.msgAccountId = res.data.map(function (item, index, array) {
          // 解构赋值
          let { id, sender } = item;
          return { label: sender, value: id };
        });
      });
    },
    getVariables(data) {
      this.ruleForm.variables = data;
    },
    save() {
      if (this.$refs.formRef.submitForm()) {
        if (this.$refs.variablesListRef) {
          this.$refs.variablesListRef.getVariables();
        }
        // 处理提交字段
        touchInsertApi({
          requestData: this.getRequestData(),
        }).then((res) => {
          let state = this.message.state(res);
          if (!state) return;
          let data = { type: this.ruleForm.id ? "edit" : "create", id: res.data.id };
          this.$emit("flushList", data);
        });
      }
    },
    // 预览
    previewTouchSource() {
      previewTouchApi({
        requestData: { ...this.getRequestData(), id: null },
      }).then((res) => {
        if (res.code !== 0) return;
        this.message.success({
          message: this.$t("预览发送成功，请到邮箱查看详情"),
        });
      });
    },
    getRequestData() {
      let { templateId, content, variables } = this.ruleForm;
      console.log(templateId);
      let requestData = {
        ...this.ruleForm,
        exclusive: 0,
        spaceId: this.$route.params.spaceId,
        content: templateId == "" ? content : "",
        variables: templateId != "" ? variables : "",
      };
      return requestData;
    },
    initTouchData() {
      let loading = this.openLoading(".touchEdit");
      detailTaskApi({
        requestData: this.touchId,
      }).then((res) => {
        // console.log("res>", res);
        if (!res) return;
        let { followId, templateId, variables } = res.data;

        this.ruleForm = {
          ...res.data,
          followId: followId === 0 ? "" : followId,
          templateId: templateId === 0 ? "" : templateId,
        };
        let value = this.templateMap.get(templateId);
        if (value) {
          value.variables = variables;
        }
        this.templateMap.set(templateId, value);
        loading.close();
      });
    },
  },
  created() {},
  mounted() {
    if (!this.touchId) this.initOptionData();
  },
};
</script>
<style lang="scss" scoped></style>
